#include "IO/ResourceManager.h"

#include "Framework/StableHeaders.h"

namespace tyro
{
	namespace IO
	{

	

		ResourceManager::ResourceManager()
			:	resourceHandleCount(0)
		{

		}

		
		tyro::IO::ResourcePtr ResourceManager::Load( const String& name, const String& groupName )
		{
			// Make sure resource is created
			ResourcePtr res = CreateOrLoad(name, groupName).first;

			// Load the resource
			res->Load();

			return res;
		}

		ResourceManager::ResourceCreateOrLoadResult ResourceManager::CreateOrLoad( const String& name, const String& groupName )
		{
			// Retrieve the resource
			ResourcePtr res = GetResourceByName(name, groupName);
			bool created = false;
			if (res.IsNull())
			{
				created = true;
				res = Create(name, groupName);
			}

			return ResourceCreateOrLoadResult(res, created);
		}

		tyro::IO::ResourcePtr ResourceManager::GetResourceByName( const String& name, const String& groupName /*= ResourceGroupManager::DEFAULT_GROUP_NAME */ )
		{
			ResourcePtr res;

			// Find resource in local pool
			if (res.IsNull())
			{

				ResourceMap::iterator itr = resources.find(name); 
				if (itr != resources.end())
				{
					res = itr->second;
				}
				else
				{

				}
			}

			return res;
			
		}

		tyro::IO::ResourcePtr ResourceManager::Create( const String& name, const String& group )
		{
			// Call the implementation of create
			ResourcePtr res = ResourcePtr(CreateImpl(name, GetNextHandle(), group));

			// Add the implementation to resource list
			AddResource(res);

			return res;
		}

		void ResourceManager::AddResource( ResourcePtr res )
		{
			// Add the resource to the list
			resources.insert(ResourceMap::value_type(res->GetName(), res));
		}

		ResourceHandle ResourceManager::GetNextHandle( void )
		{
			// Allocate the next resource handle
			return resourceHandleCount++;
		}

	}
}